<template>
<div>
  <Breadcrumb></Breadcrumb>
<!--  卡片视图-->
  <el-card>
<!--    警告区域-->
    <el-alert show-icon title="注意：只允许为第三级分类设置相关参数!" type="warning" :closable="false"></el-alert>
    <el-row class="cat_opt"  >
      <el-col >
      <span style="margin-right: 10px;">选择商品分类:</span>
<!--        选择商品分类的级联选择框-->
        <el-cascader
            clearable
            change-on-select
            expand-trigger="hover"
            v-model="selectedKeys"
            :props="cateProps"
            :options="cateList"
            @change="handleChange" ></el-cascader>

      </el-col>
    </el-row>
    <!--    tab页签区域-->
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addParamsDialogShow">添加参数</el-button>
<!--        动态参数表格-->
        <el-table :data="manyTableData" border stripe style="margin-top: 10px">
          <el-table-column type="expand">
            <template slot-scope="scope">
                  <el-tag style="margin-left: 10px;margin-top: 10px" v-for="(item,i) in scope.row.attr_vals" @close="handleClose(i,scope.row)" :key="i" closable >
                    {{item}}
                  </el-tag>
                  <el-input
                      style="margin-left: 10px;margin-top: 10px"
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!--              添加按钮-->
                  <el-button style="margin-left: 10px"  v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>


            </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditDialog(scope.row)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态参数" name="only" :disabled="isBtnDisabled">
        <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addParamsDialogShow">添加属性</el-button>
        <el-table :data="onlyTableData" border stripe>
          <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag style="margin-left: 10px;margin-top: 10px" v-for="(item,i) in scope.row.attr_vals" @close="handleClose(i,scope.row)" :key="i" closable >
                  {{item}}
                </el-tag>
                <el-input
                    style="margin-left: 10px;margin-top: 10px"
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!--              添加按钮-->
                <el-button style="margin-left: 10px"  v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>


              </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="属性名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditDialog(scope.row)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-card>
<!--  添加参数对话框-->
  <el-dialog
      :title="titleText"
      :visible.sync="addParamsDialogVisible"
      width="40%"
      @close="addClosed"
       >
    <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules" >
      <el-form-item :label="titleText" prop="attr_name">
        <el-input v-model="addForm.attr_name"></el-input>
      </el-form-item>


    </el-form>
    <span slot="footer" class="dialog-footer">
          <el-button @click="addParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
  </el-dialog>
  <!--  修改参数对话框-->
  <el-dialog
      :title="titleText"
      :visible.sync="editParamsDialogVisible"
      width="40%"
      @close="addClosed"
  >
    <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editFormRules" >
      <el-form-item :label="titleText" prop="attr_name">
        <el-input v-model="editForm.attr_name"></el-input>
      </el-form-item>


    </el-form>
    <span slot="footer" class="dialog-footer">
          <el-button @click="editParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
  </el-dialog>
</div>
</template>

<script>
import Breadcrumb from "@/components/Breadcrumb";

export default {
  name: "params",
  components:{
    Breadcrumb
  },
  data() {
    return {
      cateList:[],
      //父级分类的列表
      parentCateList:[],
      //指定级联选择器的配置对象
      cateProps:{
        value:'cat_id',
        label:'cat_name',
        children:'children',
      },
      //选中的父级分类的id数组
      selectedKeys:[],
      activeName:'many',
      manyTableData:[],
      onlyTableData:[],
      addParamsDialogVisible:false,
      addForm:{},
      addFormRules:{
        attr_name:[
          {required: true, message: "请输入", trigger: "blur"}
        ]
      },
      editParamsDialogVisible:false,
      editFormRules:{
        attr_name:[
          {required: true, message: "请输入", trigger: "blur"}
        ]
      },
      editForm:{},
      inputVisible:false,
      inputValue:'',




    }
  },
  created() {
    this.getCateList();
  },
  computed:{

    //如果按钮需要被禁用则返回true 否则返回false
    isBtnDisabled(){
      if (this.selectedKeys.length!==3){
        return true
      }
      return false
    },
    //当前选中规定三级分类的id
    cateId(){
      if (this.selectedKeys.length===3){
        return this.selectedKeys[2]
      }
      return null;
    },
    titleText(){
      if(this.activeName==='many'){
        return '动态参数'
      }
      return '静态属性'
    }
  },
  methods:{
    //删除对应的参数和选项和
    handleClose(i,row){
      row.attr_vals.splice(i,1);
      this.saveAttrVals(row)
    },
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = '';
        row.inputVisible = false;
        return
      }
      //如果没有return则输入了内容需要做处理
      row.attr_vals.push(row.inputValue.trim())
      console.log(row.attr_vals);
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    async saveAttrVals(row) {
      try {
        const {data: res} = await this.axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
            {
              attr_name: row.attr_name,
              attr_sel: row.attr_sel,
              attr_vals: row.attr_vals.join(',')
            }
        );
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)

      } catch (e) {
        this.$message.error("服务器出错请联系管理员")
      }
    },
    showInput(row){
      row.inputVisible=true;
      this.$nextTick(()=>{
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    deleteParams(attr_id){
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const {data: res} = await this.axios.delete(`categories/${this.cateId}/attributes/${attr_id}`);
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.getParamsData()
        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    editParams(){
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return;
        }
        try {
          const {data: res} = await this.axios.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {attr_name:this.editForm.attr_name,attr_sel:this.activeName});
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.editParamsDialogVisible=false;
          this.getParamsData()
          this.$message.success(res.meta.msg)

        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      })
    },
    async showeditDialog(row) {
      try {
        const {data: res} = await this.axios.get(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          params:{
            attr_sel:this.activeName
          }
        });
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.editForm=res.data
        this.$message.success(res.meta.msg)

      } catch (e) {
        this.$message.error("服务器出错请联系管理员")
      }
      this.editParamsDialogVisible = true;
    },
    addParams(){
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return;
        }
        try {
          const {data: res} = await this.axios.post('categories/'+this.cateId+'/attributes', {attr_name:this.addForm.attr_name,attr_sel:this.activeName});
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }
          this.addParamsDialogVisible=false;
          this.getParamsData()
          this.$message.success(res.meta.msg)

        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      })
    },
    addClosed(){
      this.$refs.addFormRef.resetFields()
    },
    addParamsDialogShow(){
      this.addParamsDialogVisible=true;
    },
    handleTabClick(){
      this.getParamsData()
    },
    async handleChange() {
     this.getParamsData()

    },
    async getParamsData() {
      if (this.selectedKeys.length != 3) {
        this.selectedKeys = []
        this.manyTableData=[]
        this.onlyTableData=[]
        return
      }
      //根据所选分类的id和当前所处的面板，获取对应的参数
      try {
        const {data: res} = await this.axios.get(`categories/${this.cateId}/attributes`, {params: {sel: this.activeName}})
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
         res.data.forEach((item)=>{
           item.attr_vals=item.attr_vals?item.attr_vals.split(','):[]
           //控制文本框的显示与隐藏
           item.inputValue=''
           //文本框中输入的值
           item.inputVisible=false
         })
        if (this.activeName==='many'){
          this.manyTableData=res.data;
        }else {
          this.onlyTableData=res.data;
        }
      } catch (e) {
        this.$message.error(e)
      }
    },
    //获取所有的商品分类列表
    async getCateList() {
      try {
        const {data: res} = await this.axios.get(`categories`);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.cateList=res.data;
      } catch (e) {
        this.$message.error(e)
      }
    },
    }

}
</script>

<style scoped>
.cat_opt{
  margin: 15px 0;
}
.input-new-tag{
  width: 120px;
}
</style>
